package pers.ascend.spring.cloud.greenwich.service.governance.eureka.consumer.mange.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.validation.constraints.NotBlank;
import java.net.URI;

/**
 * 说明：
 *
 * @author ascend
 * 2021/3/16 7:45
 */
@RestController
@RequestMapping(value = "/consumer")
@Validated
public class EurekaConsumerController {
    protected Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping(value = "/hello")
    public String hello(@RequestParam("name") @NotBlank String name) {
        ServiceInstance service = loadBalancerClient.choose("eureka-producer");
        if (log.isInfoEnabled()) {
            System.out.println("service = " + service);
        }
        URI uri = UriComponentsBuilder.fromUri(service.getUri()).path("/producer/hello").queryParam("name", name).build().toUri();
        return restTemplate.getForObject(uri, String.class);
    }
}
